package redis

import (
	log "aggregation/collector/logger"
	"context"
	"fmt"
	"strconv"
	"time"
)

type cache struct {
}

const (
	PREFIX = "aggregation:dashboard"
	// 最多缓存两年数据，因为计算同比环比的缘故
	EXPIRE = 60 * 60 * 24 * time.Second
)

var DashboardCache = &cache{}

// 改用redis list实现，逻辑更加简单点

// AddOneDayCount 每天添加需要一个定时任务按照时间点去触发
func (d *cache) AddOneDayCount(ctx context.Context, group, key string, count int64) (int64, error) {
	realKey := fmt.Sprintf("%s:%s:%s:%s", PREFIX, "list", group, key)
	return KV.RPush(ctx, realKey, count).Result()
}

func (d *cache) GetOneDayCount(ctx context.Context, group, key string, day int64) (int64, error) {
	realKey := fmt.Sprintf("%s:%s:%s:%s", PREFIX, "list", group, key)
	v, err := KV.LIndex(ctx, realKey, day).Result()
	if err != nil {
		return 0, err
	}
	count, err := strconv.ParseInt(v, 10, 64)
	if err != nil {
		return 0, err
	}
	return count, err
}

func (d *cache) GetListItems(ctx context.Context, group, key string) ([]int64, error) {
	realKey := fmt.Sprintf("%s:%s:%s:%s", PREFIX, "list", group, key)
	list, err := KV.LRange(ctx, realKey, 0, -1).Result()
	if err != nil {
		return nil, err
	}
	retList := make([]int64, len(list))
	for i := 0; i < len(list); i++ {
		retList[i], err = strconv.ParseInt(list[i], 10, 64)
		if err != nil {
			return nil, err
		}
	}
	return retList, err
}

func (d *cache) AddBatch(ctx context.Context, group, key string, counts ...int64) (int64, error) {
	realKey := fmt.Sprintf("%s:%s:%s:%s", PREFIX, "list", group, key)
	// 先删除原来缓存数据
	KV.Del(ctx, realKey)
	// 转成interface数组
	c := make([]interface{}, len(counts))
	for i, v := range counts {
		c[i] = v
	}
	flag, err := KV.RPush(ctx, realKey, c...).Result()
	if err != nil {
		return flag, err
	}
	//配置过期时间
	d.Expire(ctx, realKey, EXPIRE)
	return flag, err
}

func (d *cache) Expire(ctx context.Context, realKey string, expire time.Duration) {
	KV.Expire(ctx, realKey, expire)
}

func (d *cache) ListSum(ctx context.Context, group, key string) (int64, error) {
	realKey := fmt.Sprintf("%s:%s:%s:%s", PREFIX, "list", group, key)
	list, _ := KV.LRange(ctx, realKey, 0, -1).Result()
	var sum int64
	for _, v := range list {
		c, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			log.Warn(err)
			return 0, err
		}
		sum += c
	}
	return sum, nil
}

func (d *cache) AddTotal(ctx context.Context, group string, key string, count int64) error {
	return KV.Set(ctx, fmt.Sprintf("%s:%s:%s:%s", PREFIX, "key", group, key), count, EXPIRE).Err()
}
func (d *cache) GetTotal(ctx context.Context, group string, key string) (int64, error) {

	count, err := KV.Get(ctx, fmt.Sprintf("%s:%s:%s:%s", PREFIX, "key", group, key)).Result()
	if err != nil {
		return 0, err
	}
	total, err := strconv.ParseInt(count, 10, 64)
	if err != nil {
		return 0, err
	}
	return total, err
}
